package com.yanqu.road.web.controller.chargecenter;

import com.alibaba.fastjson.JSONObject;
import com.yanqu.road.entity.servercenter.ServerInfo;
import com.yanqu.road.entity.web.HttpJsonWebParam;
import com.yanqu.road.logic.config.ChannelConfig;
import com.yanqu.road.server.manger.ServerListMgr;
import com.yanqu.road.utils.http.HttpHelper;
import com.yanqu.road.web.WebServer;
import com.yanqu.road.web.controller.BaseJsonHttpServlet;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet(urlPatterns = "/androidRechargeNotify")
public class AndroidRechargeNotify extends BaseJsonHttpServlet {

	private static final long serialVersionUID = -4145213831008546653L;

	private static Logger logger = LogManager.getLogger(AndroidRechargeNotify.class.getName());

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doPost(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		logger.info("request androidRechargeNotify");
		HttpJsonWebParam httpJsonWebParam = super.parseRequest(request);
		JSONObject paramObj = httpJsonWebParam.getParamObj();
		int serverId;
		try{
			serverId = paramObj.getIntValue("serverID");
		}catch (Exception e){
			logger.error("androidRechargeNotify argument error:" + e);
			sendResult(response, 0, "serverID args error");
			return;
		}
		if(WebServer.getInstance().isNeedSend() && ServerListMgr.isCnMergeServer(serverId)){
			// 转发消息到对应的服务器上
			String result = HttpHelper.doPostJson(ChannelConfig.RECHARGE_SEND_URL + "androidRechargeNotify", paramObj.toJSONString(), "UTF-8");
			sendMessage(response, result);
			return;
		}
		ServerInfo serverInfo = ServerListMgr.getServerInfo(serverId);
		if (serverInfo == null) {
			logger.error("androidRechargeNotify no find serverId:{}", serverId);
			sendResult(response, 0, "serverID no find");
			return;
		}

		// 转发消息到对应的服务器上
		String result = HttpHelper.doPostJson(serverInfo.getWebServerUrl() + "/androidRecharge", paramObj.toJSONString(), "UTF-8");
		sendMessage(response, result);
	}
}
